package com.sg.business.model;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.BasicBSONList;
import org.bson.types.ObjectId;

import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class NoticeProvider implements INoticeProvider {
	
	private PrimaryObject po;

	public NoticeProvider(PrimaryObject po) {
		this.po = po;
	}

	@Override
	public void doCopyEventNoticeRules(INoticeProvider np) {
		List<?> rule = np.getRuleData();
		po.getCollection().update(
				new BasicDBObject().append(PrimaryObject.F__ID, po.get_id()),
				new BasicDBObject().append("$set",
						new BasicDBObject().append(F_EVENT_NOTICE_RULES, rule)));
		po.setValue(F_EVENT_NOTICE_RULES, rule);
	}
	
	public List<WorkEventNoticeRule> getRules() {
		ArrayList<WorkEventNoticeRule> result = new ArrayList<WorkEventNoticeRule>();
		Object value = po.getValue(F_EVENT_NOTICE_RULES);
		if (value instanceof List<?>) {
			List<?> list = ((List<?>) value);
			for (int i = 0; i < list.size(); i++) {
				result.add(ModelService.createModelObject(
						(DBObject) list.get(i), WorkEventNoticeRule.class));
			}
		}
		return result;
	}

	public void addRule(WorkEventNoticeRule rule) {
		Object value = po.getValue(F_EVENT_NOTICE_RULES);
		if (!(value instanceof List<?>)) {
			value = new BasicDBList();
			po.setValue(F_EVENT_NOTICE_RULES, value);
		}
		((BasicBSONList) value).add(rule.get_data());
	}

	public void removeRule(ObjectId id) {
		Object value = po.getValue(F_EVENT_NOTICE_RULES);
		if (!(value instanceof List<?>)) {
			return;
		}
		List<?> rules = (List<?>) value;
		for (Object rule : rules) {
			if (rule instanceof DBObject
					&& (id.equals(((DBObject) rule).get(PrimaryObject.F__ID)))) {
				rules.remove(rule);
				break;
			}
		}
	}

	@Override
	public String getNoticeName() {
		String desc = po.getDesc();
		if(desc == null){
			return "";
		}
		return desc;
	}

	@Override
	public Organization getOrganization() {
		return null;
	}

	@Override
	public void setNoticeName(String text) {
		//do nothing
	}

	@Override
	public boolean hasRules() {
		List<?> rulesData = getRuleData();
		return rulesData!=null&&rulesData.size()>0;
	}

	@Override
	public List<?> getRuleData() {
		return (List<?>) po.getValue(F_EVENT_NOTICE_RULES);
	}



}
